<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-1-9
 * Time: 下午4:49
 * 电桩管理
 */
namespace Service\Controller;
use Mcit\Page;
class EvchargerController extends BaseController {

    //首页
    public function index(){

        $area       = str_pad(session("area"),4,"0",STR_PAD_LEFT);;//当前运营商区号
        $location   = session("location");
        $str        = strsToArray($location);
        $evc_number = I('evc_number');
        $key_link   = I('key_link');
        if(!empty($_GET['evc_number'])){
            $sql  = "select * from ev_char a
                 left join ev_plant b
                 on b.id = a.ev_plant_id
                 where substring(a.key_link,1,4) = '$area'
                 and a.evc_number like '$evc_number%'";
        }elseif(!empty($_GET['key_link'])){
            $sql  = "select * from ev_char a
                 left join ev_plant b
                 on b.id = a.ev_plant_id
                 where substring(a.key_link,1,4) = '$area'
                 and a.key_link like '$key_link%'";
        }elseif(!empty($_GET['location_t_1']) && $location == ($_GET['location_f_1'].",".$_GET['location_s_1'])){
            if(I('location_s_1') == I('location_t_1')-1){
                $location = I('location_f_1').",".I('location_s_1');
            }else{
                $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
            }
            $sql = "select * from ev_char a
                 left join ev_plant b
                 on b.id = a.ev_plant_id
                 where substring(a.key_link,1,4) = '$area'
                and b.location like '$location%'";
        }else{
            $sql  = "select * from ev_char a
                 left join ev_plant b
                 on b.id = a.ev_plant_id
                 where substring(a.key_link,1,4) = '$area'";
        }

        //分页
        $count = count(M()->query($sql));
        // 重搜一律回第一页
        if( $_GET['fsign'] == "abnormal" ){
            $_GET['fsign'] = "normal";
            $_GET['page']  = 1;
        }
        vendor('Mcit.Sys.Page');
        $Page = new Page($count, 20);
        $pageView = $Page->show();
        $this->assign('pageView', $pageView); //发送分页
        $nowPage = isset($_GET['page']) ? $_GET['page'] * 20 - 20 : 0;
        if(!empty($_GET['evc_number'])){
            $sql1  = "select a.id,a.evc_number,a.key_link,a.evc_type,a.evc_quantity,a.card_wifi,a.sys_creat_time,b.name,b.name,b.location from ev_char a
                 left join ev_plant b
                 on b.id = a.ev_plant_id
                 where substring(a.key_link,1,4) = '$area'
                 and a.evc_number like '$evc_number%'
                 limit $nowPage,".$Page->listRows;
        }elseif(!empty($_GET['key_link'])){
            $sql1  = "select a.id,a.evc_number,a.key_link,a.evc_type,a.evc_quantity,a.card_wifi,a.sys_creat_time,b.name,b.name,b.location from ev_char a
                 left join ev_plant b
                 on b.id = a.ev_plant_id
                 where substring(a.key_link,1,4) = '$area'
                 and a.key_link like '$key_link%'
                 limit $nowPage,".$Page->listRows;
        }elseif(!empty($_GET['location_t_1']) && session("location") == ($_GET['location_f_1'].",".$_GET['location_s_1'])){
            if(I('location_s_1') == I('location_t_1')-1){
                $location = I('location_f_1').",".I('location_s_1');
            }else{
                $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
            }
            $sql1 = "select a.id,a.evc_number,a.key_link,a.evc_type,a.evc_quantity,a.card_wifi,a.sys_creat_time,b.name,b.name,b.location from ev_char a
                 left join ev_plant b
                 on b.id = a.ev_plant_id
                 where substring(a.key_link,1,4) = '$area'
                 and b.location like '$location%'
                 limit $nowPage,".$Page->listRows;
        }else{
            $sql1  = "select a.id,a.evc_number,a.key_link,a.evc_type,a.evc_quantity,a.card_wifi,a.sys_creat_time,b.name,b.name,b.location from ev_char a
                 left join ev_plant b
                 on b.id = a.ev_plant_id
                 where substring(a.key_link,1,4) = '$area'
                 limit $nowPage,".$Page->listRows;
        }
        $ev_char = M()->query($sql1);
//        echo M()->getLastSql();
        //分页结束
        foreach($ev_char as $k=>$v){
            $region_arr = strsToArray($v['location']);//查所在地
            $region = D("Admin/Region")->where("code='".$region_arr[2]."'")->getField('fullname');
            $ev_char[$k]['plant_name'] = $v['name'];//站点名称
            if(mb_strlen($v['name'],'utf-8') <= 17){
                $ev_char[$k]['plant_name_text'] = $v['name'];
            }else{
                $ev_char[$k]['plant_name_text'] = mb_substr($v['name'],0,17,"utf-8")."···";
            }
            $ev_char[$k]['region_text'] = $region;
        }
        $this->assign('ev_char',$ev_char);
        $this->china = D("Admin/Region")->getDowntown($str['0']);//当前省下所有市区县
        $this->display();
    }

    //生成运营二维码   str_pad(1,8,"0",STR_PAD_LEFT);不足向左补零 例：00000001
    public function createEvcNumber(){
        $id  = I("id");
        $key = substr(I("key_link"),0,4);
        $map['key_link'] = array("like",$key."%");
        $max_evc_number = M("char")->where($map)->max("evc_number");
        if($max_evc_number != ''){
            $data['evc_number'] = str_pad($max_evc_number + 1,12,"0",STR_PAD_LEFT);
            $result = M("char")->where("id=".$id)->save($data);
            if($result){
                //执行运营二维码下发指令
                $num = M("char")->where("id='".$id."'")->find();
                $url = 'http://id.dz.tt/index.php?m=content&c=api_v3&a=setEv2Code1&addr='.$num['key_link'].'&ev2code='.$num['evc_number'];
                responseURL($url);
                $return['state'] = 100;
                $return['msg'] = "生成成功！";
            }else{
                $return['msg'] = "生成失败，请重试！";
            }
        }else{
            $data['evc_number'] = $key."00000001";
            $result = M("char")->where("id=".$id)->save($data);
            if($result){
                //执行运营二维码下发指令
                $num = M("char")->where("id='".$id."'")->find();
                $url = 'http://id.dz.tt/index.php?m=content&c=api_v3&a=setEv2Code1&addr='.$num['key_link'].'&ev2code='.$num['evc_number'];
                responseURL($url);
                $return['state'] = 100;
                $return['msg'] = "生成成功！";
            }else{
                $return['msg'] = "生成失败，请重试！";
            }
        }
        echo json_encode($return);
        exit;
    }
    //搜索站点
    public function AjaxPlantSearch()
    {
        if (IS_AJAX) {

            if(session("location") == (I("location_f_1").",".I('location_s_1'))){
                if(I('location_s_1') == I('location_t_1')-1){
                    $location = I('location_f_1').",".I('location_s_1');
                }else{
                    $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                }
                $data['location'] = array('like','%'.$location.'%');
                $site = M("plant")->where($data)->order("id")->select();
                $return = "";
                foreach($site as $v){
                    $return .="<span>站点名称：</span><a href='javascript:void(0);' data-nid=".$v[id]." data-pid=".$v[total_ev]." data-dismiss='modal' data-id=".$v[evc_type]." class='siteSelect'>" . $v[name] . "</a><br/>
                <span style='margin-bottom: 5px;' class='companyAddr'>地　　址：".$v[address]."</span><br/><br/>";
                }
            }else{
                $return = "<span class='alert-danger'>选择与当前地区有误，请重新选择！</span>";
            }
            echo $return;
        }
    }
    //查看电桩详细信息
    public function detail(){
        if(IS_GET){
            $data = M("char")->where("id='".$_GET['id']."'")->find();
            $key_link = substr($data['key_link'],0,12);
            $plant = M("plant")->where("id='".$data['ev_plant_id']."' or station_key='".$key_link."'")->field("location,name,station_key")->find();
            $region = strsToArray($plant['location']);
            $region_text = D("Admin/Region")->where("code='".$region[2]."'")->getField("fullname");
            $data['name'] = $plant['name'];
            $data['location_text'] = $region_text;
            $data['station_key']   = $plant['station_key'];
            $trademark = M("fac")->where("fac_login_name=".$data['ev_fac_code'])->find();
            $data['trademark']     = $trademark['name'];
            $data['ev_fac_code']   = $trademark['fac_name'];
            $this->data = $data;
        }
        $this->display();
    }
    //修改电桩基础信息
    public function update(){
        if(IS_GET){
            $charOne = M("char")->where("id='".I('id')."'")->find();
            $key_link = substr($charOne['key_link'],0,12);
            $plantOne = M("plant")->where("id='".$charOne['ev_plant_id']."' or station_key='".$key_link."'")->field("name,total_ev")->find();
            $charOne['name'] = $plantOne['name'];
            $charOne['total_ev'] = $plantOne['total_ev'];
            $fac = M("fac")->where("id=".$charOne['ev_fac_code'])->find();
            $factory1 = M("device_type")->where("id=".$charOne['ev_fac_type1'])->find();
            $factory2 = M("device_type")->where("id=".$charOne['ev_fac_type2'])->find();
            $charOne['ev_fac_codeText'] = $fac['fac_name'].",".$factory1['name'].",".$factory2['name'];
            $charOne['fac'] = $fac['id'].",".$factory1['id'].",".$factory2['id'];
            $this->charOne = $charOne;
        }
        if(IS_POST){
            $id          = I("id");
            $ev_plant_id = I("ev_plant_id");
            $char = M("char")->where("id='".I('id')."'")->find();
            if($char['evc_number'] != $_POST['evc_number']){
                //运营二维码发生变更，执行运营二维码下发指令
                $url = 'http://id.dz.tt/index.php?m=content&c=api_v3&a=setEv2Code1&addr='.$char['key_link'].'&ev2code='.$_POST['evc_number'];
            }
            if($char['ev_plant_id'] != $ev_plant_id){
                $plant_1 = M("plant")->where("id='".$char['ev_plant_id']."'")->find();
                if($plant_1['total_ev'] != '' && $plant_1['total_ev'] != 0){
                    $maps['total_ev'] = $plant_1['total_ev'] - 1;
                    if($char['evc_quantity'] == 1){
                        $maps['total_par']   = $plant_1['total_par'] - 1;
                    }else{
                        $maps['total_par']   = $plant_1['total_par'] - 2;
                    }
                    M("plant")->where("id='".$char['ev_plant_id']."'")->save($maps);
                }
                $plant = M("plant")->where("id='".$ev_plant_id."'")->find();
                $map['total_ev']    = $plant['total_ev'] + 1;
                if($char['evc_quantity'] == 1){
                    $map['total_par']   = $plant['total_par'] +1;
                }else{
                    $map['total_par']   = $plant['total_par'] +2;
                }
                M("plant")->where("id='".$ev_plant_id."'")->save($map);
                $data['ev_plant_id'] = $ev_plant_id;
                $data['evc_number']  = I("evc_number");
                $data['wifi']        = I("wifi");
                $data['card_wifi']   = I("card_wifi");
                $data['card_gprg']   = I("card_gprg");
                $data['charID']      = I("charID");
                $result = M("char")->where("id='".$id."'")->save($data);
                if($result > 0){
                    responseURL($url);
                    $this->redirect("Evcharger/index");
                }else{
                    $this->error("保存失败，请重试！");
                }
            }else{
                $datas['evc_number']  = I("evc_number");
                $datas['wifi']        = I("wifi");
                $datas['card_wifi']   = I("card_wifi");
                $datas['card_gprg']   = I("card_gprg");
                $datas['charID']      = I("charID");
                $datas['ev_plant_id'] = $ev_plant_id;
                $result = M("char")->where("id='".$id."'")->save($datas);
                if($result > 0){
                    responseURL($url);
                    $this->redirect("Evcharger/index");
                }else{
                    $this->redirect("Evcharger/index");
                }
            }
        }
        $str=strsToArray(session('location'));
        $this->china = D("Admin/Region")->getDowntown($str['0']);
        $this->display();
    }
    //批量编辑电桩所属站点
    public function editplant(){
        if(IS_AJAX){
            $charids = strsToArray(I("charids"));
            $plantid = I("plantid");
            $plant   = M("plant")->where("id='".$plantid."'")->find();
            $datas['total_ev']  = $plant['total_ev'] + count($charids);
            $datas['total_par'] = $plant['total_par'] + count($charids);
            $results = M("plant")->where("id='".$plantid."'")->save($datas);
            if($results){
                $map['id'] = array("IN",$charids);
                $data['ev_plant_id'] = $plantid;
                $result = M("char")->where($map)->save($data);
                if($result){
                    $return['state'] = 100;
                    $return['url']   = U('Evcharger/index');
                }else{
                    $return['state'] = 200;
                    $return['msg']   = '保存失败！';
                }
            }else{
                $return['state'] = 200;
                $return['msg']   = '保存失败！';
            }
            echo json_encode($return);
            exit;
        }
//        $this->china = D("Admin/Region")->getChinaArea();
        $str=strsToArray(session('location'));
        $this->china = D("Admin/Region")->getDowntown($str['0']);
        $this->display();
    }
}